window.addEventListener("message", async function (event) {
    //处理页面响应的消息
    if (event.data.from === "web") {
        if (event.data.action == "telemetry") {
            let telemetry = event.data.data;
            await postToken(telemetry);
        }
        // console.log("rev web response: " + JSON.stringify(event.data))
    } else {
        if (event.data.from != "extenstion") {
            // console.log(event)
        }
    }

});

let first = true;

async function postToken(telemetry) {
    let api = "https://meiri56.com/rest-api/token/update/v2";
    let data = {data: telemetry, hostCode: 'msk'}
    //post body需要转成json字符串
    //post form传对象
    ajax(api, JSON.stringify(data), {method: "post"}, function (res) {
        if (first) {
            first = false;
            console.log(res)
        }
    })
}

chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
    //收到popup.js的消息，影响处理
    if (request.type == 'telemetry') {
        let message1 = {"from": "extenstion", "action": "telemetry"};
        window.postMessage(message1, "*");
        sendResponse('success')
    }
    return true;
});